package cn.shentianlan.service.impl;

import cn.shentianlan.criteria.BaseCriteria;
import cn.shentianlan.criteria.CourseCriteria;
import cn.shentianlan.domain.dto.CourseDTO;
import cn.shentianlan.domain.entity.Clazz;
import cn.shentianlan.domain.entity.Course;
import cn.shentianlan.mapper.CourseMapper;
import cn.shentianlan.service.CourseService;
import cn.shentianlan.utils.BaseUtils;
import cn.shentianlan.utils.DataUtils;
import cn.shentianlan.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 陈俊源
 * @Description TODO
 * @Date 2021/4/20
 * @Version 1.0
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public Result saveOrUpdateCourse(CourseDTO courseDTO) {
        Course course = BaseUtils.copyProperties(courseDTO, Course.class);
        if (courseDTO.getId()==null){
            Long id = DataUtils.assignId();
            course.setId(id);
            courseMapper.save(course);
        }else{
            courseMapper.update(course);
        }
        return Result.success(course.getId());
    }

    @Override
    public Result findCourseByCourseCriteria(CourseCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(),criteria.getPageSize(),false);
        List<Course> courseList = courseMapper.findCourseByCourseCriteria(criteria);
        Integer count = courseMapper.getCount(criteria);
        List<CourseDTO> courseDTOList = new ArrayList<CourseDTO>();
        for (Course course :courseList ) {
            CourseDTO courseDTO = bulidCourseDTO(course);
            courseDTOList.add(courseDTO);
        }
        PageInfo<CourseDTO> pageInfo = new PageInfo<>(courseDTOList);
        pageInfo.setTotal(count.longValue());
        return Result.success(pageInfo);
    }

    @Override
    public Result getCourseById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法查询到课程信息");
        }
        Course course = courseMapper.getCourseById(id);
        if (course == null){
            return Result.fail("获取该id对应的课程信息出错");
        }
        return Result.success(course);
    }

    @Override
    public Result deleteCourseById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法查询到课程信息");
        }
        Course course = courseMapper.getCourseById(id);
        if (course == null){
            return Result.fail("获取该id对应的课程信息出错");
        }
        courseMapper.deleteCourseById(id);
        return Result.success(id);
    }

    private CourseDTO bulidCourseDTO(Course course) {
        CourseDTO courseDTO = BaseUtils.copyProperties(course, CourseDTO.class);
        return courseDTO;
    }
}
